package com.example.cry.mediacodecimagereaderchain;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cry.mediametaretriverwrapper.MediaMetadataRetrieverWrapper;
import com.cry.mediametaretriverwrapper.RetrieverProcessThread;
import com.example.cry.mediacodecimagereaderchain.codec.VideoProcessThread;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {



    private VideoProcessThread mVideoProcessThread;
    private ProgressDialog mProgressDialog;
    private ListView mListView;
    private ListView mListView2;
    private ArrayList<Double> length=new ArrayList<Double>();//用于保存测量数据的长度
    private ArrayList<String> mVideoPaths = new ArrayList<>();
    private VideoPathAdapter mPathAdapter;//视频路径适配器
    private BitmapAdapter mBitmapAdapter;//bitmap适配器
    private BitmapAdapter mBitmapAdapter2;
    Bitmap all=Bitmap.createBitmap(1,1, Bitmap.Config.ARGB_8888);
    double Photo_size =2;
    private BitmapShow bitmapShow = new BitmapShow();

    ArrayList<Bitmap> bitmapArrayList = new ArrayList<>();//bitmap列表


    private String targetPath;
    MediaMetadataRetrieverWrapper metadataRetriever;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        length.add(0.1);
        for (int i =0;i<2000;i++)
        {
            if (i%2==0)
            {
                length.add(0.2+length.get(i));
            }
            else if(i%3==0)
            {
                length.add(0.3+length.get(i));
            }
            else if(i%5==0)
            {
                length.add(0.4+length.get(i));
            }
            else
            {
                length.add(0.1+length.get(i));
            }


        }

        mListView = (ListView) findViewById(R.id.list_view);//绑定视频文件窗口
        mPathAdapter = new VideoPathAdapter(mVideoPaths);//初始化视频路径适配器
        mBitmapAdapter = new BitmapAdapter(bitmapArrayList);//初始化bitmap适配器
        mBitmapAdapter2 = new BitmapAdapter(bitmapArrayList);
        mListView2 = (ListView) findViewById(R.id.list_view2);
        mListView2.setAdapter(mBitmapAdapter);
        mListView.setAdapter(mPathAdapter);//将视频路径委托添加到视频窗口视图层
        mListView.bringToFront();

        //绑定显示图片窗口
//        mIvFrame = (ImageView) findViewById(R.id.iv_frame);



//        mListView3 = (ListView) findViewById(R.id.list_view3);
//        mIvFrame = (ImageView) findViewById(R.id.iv_frame);
//        mBitmapAdapter2 = new BitmapAdapter(bitmapArrayList2);
//        mListView3.setAdapter(mBitmapAdapter2);

//判断是否获得内存读写权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
        } else {
            getVideoFiles();//获取视频文件
        }
//获取屏幕大小
//        Display defaultDisplay = getWindowManager().getDefaultDisplay();
//        DisplayMetrics displayMetrics = new DisplayMetrics();
//        defaultDisplay.getMetrics(displayMetrics);
//        int widthPixels = displayMetrics.widthPixels;
//        int heightPixels = displayMetrics.heightPixels;

    }

    @SuppressLint("NewApi")
    private void getVideoFiles() {
        mVideoProcessThread = new VideoProcessThread(this);//获取视频线程
        mProgressDialog = new ProgressDialog(this);//进度对话框
        mProgressDialog.setMessage("获取视频列表");
        mProgressDialog.show();
        mVideoProcessThread.getFileList(new VideoProcessThread.VideoListCallBack() {
            @Override
            public void onComplete(final ArrayList<String> videos) {//获取视频列表
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mProgressDialog.dismiss();

                        mVideoPaths.addAll(videos);

                        mPathAdapter.notifyDataSetChanged();//更新视频路径委托器

                    }
                }
                );
            }
        });
//视频列表窗口点击监听
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

//视频列表条目点击监听
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {



//                Log.d("position", "position = " + position);
                String path = mVideoPaths.get(position);
                targetPath = path;//保存点击的视频路径字符串

                //初始化MediaMetadataRetrieverWrapper类
                MediaMetadataRetrieverWrapper metadataRetriever = new MediaMetadataRetrieverWrapper();
                metadataRetriever.forceFallBack(true);
                metadataRetriever.setDataSource(path);//设置文件路径







                final int[] i = {0,1};

                metadataRetriever.getFramesInterval(125,1, new RetrieverProcessThread.BitmapCallBack() {

                    @Override
                    public void onComplete(final Bitmap frame) {

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {


                                int width = frame.getWidth();
                                if(bitmapArrayList.size()>0) {

                                    all = bitmapArrayList.get(bitmapArrayList.size()-1).copy(Bitmap.Config.ARGB_8888, true);

                                }

                                double realsize =0;
                                if (i[0] >0)
                                {
                                    if (length.get(i[0])-length.get(i[0] -1)>0)
                                    {
                                        realsize=(length.get(i[0])-length.get(i[0] -1))/Photo_size;
                                    }
                                }


                                all=newBitmap(width,realsize,all,frame);
                                i[0]++;
                                if (all.getHeight()>1024*4)
                                {
                                    Bitmap topBitmap = Bitmap.createBitmap(all, 0, 0, all.getWidth(), 1024*4);

                                    bitmapArrayList.add(topBitmap);
                                    saveBitmap("9-"+i[1],topBitmap);
                                    i[1]++;
                                    all=Bitmap.createBitmap(all, 0, 1024*4, all.getWidth(),
                                            all.getHeight() - 1024*4);

                                }

                                    bitmapArrayList.clear();
                                mBitmapAdapter2.notifyDataSetInvalidated();

//

                                bitmapArrayList.add(all);//图像列表添加frame对象

                                mBitmapAdapter.notifyDataSetChanged();



                            }



                        }





                        );
                        saveBitmap("9-last",all);
//                        bitmapArrayList.clear();









                    }




                });












//                }
                //2S
//                metadataRetriever.getFrameAtTime(2 * 1000 * 1000, 2, new RetrieverProcessThread.BitmapCallBack() {
//                    @Override
//                    public void onComplete(final Bitmap frame) {
//                        long end = System.currentTimeMillis();
//                        Log.d("zzx", "cost ms = " + (end - start));
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                bitmapArrayList.add(frame);
//                                mBitmapAdapter.notifyDataSetChanged();
//                            }
//                        });
//                    }
//                });

            }

        });
    }



    public static Bitmap newBitmap(int width, double relsize,Bitmap bit1, Bitmap bit2) {
        if (width <= 0) {
            return null;
        }

        int h1 =  bit1.getHeight();
        int h2 = bit2.getHeight() ;
        int height =(int) (h1 + h2*relsize); //缩放到屏幕宽度时候 合成后的总高度
        //创建一个空的Bitmap(内存区域),宽度等于第一张图片的宽度，高度等于两张图片高度总和
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);



        //将bitmap放置到绘制区域,并将要拼接的图片绘制到指定内存区域
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(bit1, 0, 0, null);
        canvas.drawBitmap(bit2, 0, h1, null);
        return bitmap;

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            getVideoFiles();
        }
    }

//    public void tap(View view) {
//        //2S
//        final long start = System.currentTimeMillis();
//
////        metadataRetriever.getFrameAtTime(2 * 1000 * 1000, 2, new RetrieverProcessThread.BitmapCallBack() {
////            @Override
////            public void onComplete(final Bitmap frame) {
////                long end = System.currentTimeMillis();
////                Log.d("zzx", "cost ms = " + (end - start));
////                runOnUiThread(new Runnable() {
////                    @Override
////                    public void run() {
////                        bitmapArrayList.add(frame);
////                        mBitmapAdapter.notifyDataSetChanged();
////                    }
////                });
////            }
////        });
//
//        MediaMetadataRetrieverWrapper metadataRetriever2 = new MediaMetadataRetrieverWrapper();
//        metadataRetriever2.setDataSource(targetPath);
////        metadataRetriever2.getFramesInterval(1000, 2, new RetrieverProcessThread.BitmapCallBack() {
////            @Override
////            public void onComplete(final Bitmap frame2) {
////                runOnUiThread(new Runnable() {
////                    @Override
////                    public void run() {
////                        bitmapArrayList2.add(frame2);
////                        mBitmapAdapter2.notifyDataSetChanged();
////                    }
////                });
////            }
////        });
//    }


    private class BitmapShow implements VideoProcessThread.BitmapCallBack {

        @Override
        public void onComplete(final Bitmap frame) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    mIvFrame.setImageBitmap(frame);
                    bitmapArrayList.add(frame);
                    mBitmapAdapter.notifyDataSetChanged();
                }
            });
        }
    }

//    private class BitmapShow2 implements VideoProcessThread.BitmapCallBack {
//
//        @Override
//        public void onComplete(final Bitmap frame) {
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
////                    mIvFrame.setImageBitmap(frame);
//                    bitmapArrayList2.add(frame);
//                    mBitmapAdapter2.notifyDataSetChanged();
//                }
//            });
//        }
//    }

    public  void saveBitmap(String bitName, Bitmap mBitmap) {
        File f = new File("/sdcard/" + bitName + ".jpg");
        try {
            f.createNewFile();
        } catch (IOException e) {
            Log.d("error", "在保存图片时出错 " );
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
            Log.d("true", "保存图片成功 " );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private class VideoPathAdapter extends BaseAdapter {

        private ArrayList<String> videoPaths;

        public VideoPathAdapter(ArrayList<String> videoPaths) {
            this.videoPaths = videoPaths;
        }

        @Override
        public int getCount() {
            return videoPaths.size();
        }

        @Override
        public String getItem(int position) {
            return videoPaths.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false);
            }

            ((TextView) convertView.findViewById(android.R.id.text1))
                    .setText(getItem(position));
            return convertView;
        }
    }


    private class BitmapAdapter extends BaseAdapter {


        private ArrayList<Bitmap> bitmaps;

        public BitmapAdapter(ArrayList<Bitmap> bitmaps) {
            this.bitmaps = bitmaps;
        }

        @Override
        public int getCount() {
            return bitmaps.size();
        }

        @Override
        public Bitmap getItem(int position) {

            return bitmaps.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.simple_image, parent, false);

            }
            ((ImageView) convertView.findViewById(R.id.image))
                    .setImageBitmap(getItem(position));

            return convertView;
        }

    }
}

